package com.hzdp.web.captcha;

import java.awt.image.BufferedImage;
import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;

import com.hzdp.cache.service.CacheService;
import com.hzdp.cache.support.CacheTypeFactory;
import com.octo.captcha.Captcha;
import com.octo.captcha.engine.CaptchaEngine;
import com.octo.captcha.service.AbstractManageableCaptchaService;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.captchastore.CaptchaStore;
import com.octo.captcha.service.image.ImageCaptchaService;

public class JCaptchaService extends AbstractManageableCaptchaService implements ImageCaptchaService {

	public static final String CacheType = "captcha";

	@Autowired
	private CacheService cacheService;

	public JCaptchaService() {
		super(new JCaptchaStore(), new JcaptchaEngine(), 0, 0, 0);
	}

	public JCaptchaService(int minGuarantedStorageDelayInSeconds, int maxCaptchaStoreSize, int captchaStoreLoadBeforeGarbageCollection) {
		super(new JCaptchaStore(), new JcaptchaEngine(), minGuarantedStorageDelayInSeconds, maxCaptchaStoreSize, captchaStoreLoadBeforeGarbageCollection);
	}

	public JCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine, int minGuarantedStorageDelayInSeconds, int maxCaptchaStoreSize,
			int captchaStoreLoadBeforeGarbageCollection) {
		super(captchaStore, captchaEngine, minGuarantedStorageDelayInSeconds, maxCaptchaStoreSize, captchaStoreLoadBeforeGarbageCollection);
	}

	public BufferedImage getImageChallengeForID(String ID) throws CaptchaServiceException {
		return (BufferedImage) getChallengeForID(ID);
	}

	public BufferedImage getImageChallengeForID(String ID, Locale locale) throws CaptchaServiceException {
		return (BufferedImage) getChallengeForID(ID, locale);
	}

	protected Object getChallengeClone(Captcha captcha) {
		BufferedImage challenge = (BufferedImage) captcha.getChallenge();
		String response = null;
		if (captcha instanceof JCaptchaGimpy) {
			response = ((JCaptchaGimpy) captcha).getResponse();
		}
		BufferedImage clone = new JCaptchaBufferedImage(challenge.getWidth(), challenge.getHeight(), challenge.getType(), response);

		clone.getGraphics().drawImage(challenge, 0, 0, clone.getWidth(), clone.getHeight(), null);
		clone.getGraphics().dispose();

		return clone;
	}

	public JCaptchaBufferedImage generate(String ID) throws CaptchaServiceException {
		JCaptchaBufferedImage toReturn = (JCaptchaBufferedImage) getImageChallengeForID(ID);
		cacheService.put(CacheTypeFactory.getCacheType(CacheType), ID, toReturn.getCaptcha());
		return toReturn;
	}

	public boolean check(String ID, String captcha) {
		Object object = cacheService.get(CacheTypeFactory.getCacheType(CacheType), ID);
		return object != null && object.toString().equalsIgnoreCase(captcha);
	}

}
